//
//  MCNNavHistoryStackContentView.swift
//  MCNNavHistoryStackContentView
//
//  Created by yhbj on 2021/9/16.
//

import UIKit

class MCNNavHistoryStackContentView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    lazy var mcn_historyStackView: MCNNavHistoryStackView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .vertical
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        let collectionView = MCNNavHistoryStackView(frame: .zero, collectionViewLayout: flowLayout)
        collectionView.backgroundColor = .white
        collectionView.clipsToBounds = true
        collectionView.layer.cornerRadius = 12
        if mcn_historyStackViewStyle == .Light {
            collectionView.backgroundColor = MCNNavHistoryStackViewStyleLightBackgroundColor
        } else {
            collectionView.backgroundColor = MCNNavHistoryStackViewStyleDarkBackgroundColor
        }
        return collectionView
    }()
    var mcn_historyStackArray: [MCNNavHistoryStackModel] = [] {
        didSet {
            if mcn_historyStackArray.count > 0 {
                let firstHistoryStackModel = mcn_historyStackArray.first
                let lastHistoryStackModel = mcn_historyStackArray.last
                firstHistoryStackModel?.isSelected = true
                selectedHistoryStackModel = firstHistoryStackModel
                lastHistoryStackModel?.isLast = false
            }
        }
    }
    var mcn_historyStackViewLeft: CGFloat = 0 {
        didSet {
            mcn_historyStackView.mcn_x = mcn_historyStackViewLeft
        }
    }
    var mcn_historyStackViewStyle: MCNNavHistoryStackViewStyle? {
        didSet {
            mcn_historyStackView.reloadData()
        }
    }
    
    private var converView = UIView()
    private var isShowed: Bool = false
    private var selectedHistoryStackModel: MCNNavHistoryStackModel?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUp()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUp() {
        addSubview(converView)
        addSubview(mcn_historyStackView)
        mcn_historyStackView.delegate = self
        mcn_historyStackView.dataSource = self
        mcn_historyStackView.register(MCNNavHistoryStackCell.classForCoder(), forCellWithReuseIdentifier: NSStringFromClass(MCNNavHistoryStackCell.classForCoder()))
        converView.isUserInteractionEnabled = true
        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(coverViewTouch))
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(coverViewTouch))
        converView.addGestureRecognizer(panGestureRecognizer)
        converView.addGestureRecognizer(tapGestureRecognizer)
        
        NotificationCenter.default.addObserver(self, selector: #selector(orientationDidChange(notification:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        frame = UIScreen.main.bounds
        converView.frame = frame
        if isShowed {
            updateHistoryStackViewFrame(hide: false)
        }
    }
    
    @objc func coverViewTouch() {
        if isShowed {
            mcn_hide()
        }
    }
    
    func mcn_show() -> MCNNavHistoryStackContentView {
        let window = MCNMainWindow
        window.addSubview(self)
        updateHistoryStackViewFrame(hide: true)
        UIView.animate(withDuration: 0.2) {
            self.converView.backgroundColor = UIColor(white: 0, alpha: 0.05)
            self.updateHistoryStackViewFrame(hide: false)
        } completion: { _ in
            self.isShowed = true
        }
        return self
    }
    
    func mcn_hide() {
        isShowed = false
        UIView.animate(withDuration: 0.15) {
            self.converView.backgroundColor = UIColor(white: 0, alpha: 0)
            self.updateHistoryStackViewFrame(hide: true)
        } completion: { _ in
            self.removeFromSuperview()
        }
    }
    
    func updateHistoryStackViewFrame(hide: Bool) {
        if hide {
            mcn_historyStackView.frame = CGRect.init(x: mcn_historyStackViewLeft + 20, y: MCNAppStutsBarHeight + MCNNavHistoryStackCellHeight / 2, width: 0, height: 0)
        } else {
            mcn_historyStackView.frame = CGRect.init(x: mcn_historyStackViewLeft, y: MCNAppStutsBarHeight, width: MCNNavHistoryStackViewWidth, height: Double(mcn_historyStackArray.count) * MCNNavHistoryStackCellHeight)
        }
    }
    
    //MARK: - collectionDelegate
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: mcn_historyStackView.frame.width, height: MCNNavHistoryStackCellHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let historyStackModel = mcn_historyStackArray[indexPath.item]
        doPopViewController(historyStackModel: historyStackModel)
    }
    
    //MARK: - collectionDatasource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return mcn_historyStackArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(MCNNavHistoryStackCell.classForCoder()), for: indexPath) as! MCNNavHistoryStackCell
        cell.historyStackViewStyle = mcn_historyStackViewStyle
        cell.historyStackModel = mcn_historyStackArray[indexPath.item]
        return cell
    }
    
    //MARK: - private
    func handlePanGesture(point: CGPoint) {
        if point.x > mcn_historyStackView.mcn_x || point.y > mcn_historyStackView.mcn_top {
            if selectedHistoryStackModel != nil {
                selectedHistoryStackModel?.isSelected = false
                selectedHistoryStackModel = nil
                mcn_historyStackView.reloadData()
            }
        } else {
            if selectedHistoryStackModel != nil {
                selectedHistoryStackModel?.isSelected = false
            }
            guard let indexPath = mcn_historyStackView.indexPathForItem(at: point) else { return }
            let historyStackModel = mcn_historyStackArray[indexPath.item]
            if !(selectedHistoryStackModel != nil && selectedHistoryStackModel == historyStackModel) {
                historyStackModel.isSelected = true
                mcn_historyStackView.reloadData()
                selectedHistoryStackModel = historyStackModel
                if #available(iOS 10.0, *) {
                    let impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .light)
                    impactFeedbackGenerator.impactOccurred()
                }
            }
        }
    }
    
    func handlePanGestureEnd() {
        doPopViewController(historyStackModel: selectedHistoryStackModel)
    }
    
    private func doPopViewController(historyStackModel: MCNNavHistoryStackModel?) {
        guard let model = historyStackModel else { return }
        guard let viewController = model.viewController else { return }
        guard let navigationController = viewController.navigationController else { return }
        navigationController.popToViewController(viewController, animated: true)
        mcn_hide()
    }
    
    @objc func orientationDidChange(notification: NSNotification) {
        if isShowed {
            mcn_hide()
        }
    }
}
